<template>
  <div>
    <el-form :model="formData" label-width="150px" ref='$$form' :rules="rules" v-loading="loading">
      <el-form-item label="优惠券名称" prop="couponName">
        <el-input clearable placeholder="请填写优惠券名称" v-model="formData.couponName" style="width: 60%"></el-input>
      </el-form-item>
      <el-form-item label="金额规则" prop="couponMoneyId">
        <el-select v-model="formData.couponMoneyId" placeholder="请选择金额规则" style="width: 60%">
          <el-option v-for="item in moneyRules" :key="item.id" :label="item.ruleName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="品类规则" prop="couponCategoryId">
        <el-select v-model="formData.couponCategoryId" style="width: 60%" placeholder="请选择品类规则">
          <el-option v-for="item in categoryRules" :key="item.id" :label="item.ruleName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="有效期规则">
        <el-radio-group v-model="formData.validateRule">
          <el-radio :label="1">固定时间段</el-radio>
          <el-radio :label="2">固定天数</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="有效期" v-if="formData.validateRule === 1" prop="dateRange">
        <el-date-picker
          v-model="formData.dateRange"
          style="width: 60%"
          start-placeholder="开始日期"
          range-separator="至"
          end-placeholder="截止日期"
          type="daterange"></el-date-picker>
      </el-form-item>
      <el-form-item label="有效期" v-if="formData.validateRule === 2" prop="validDays">
        <el-input v-model="formData.validDays" style="width:60%">
          <template slot="append">天</template>
        </el-input>
      </el-form-item>
    </el-form>
    <div class='btn-area'>
      <el-button type="primary" @click='doSubmit'>{{btnText}}</el-button>
      <el-button @click="$emit('close')">取消</el-button>
    </div>
  </div>
</template>

<script>
import dayjs from 'dayjs'

export default {
  name: 'PartalCouponView',
  props: {
    data: {
      type: Object,
      default: () => ({})
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        couponName: '',
        couponMoneyId: undefined,
        couponCategoryId: undefined,
        validateRule: 1,
        dateRange: [],
        validDays: undefined,
        isActive: 0
      },
      loading: true,
      moneyRules: [],
      categoryRules: [],
      rules: {
        couponName: [
          { required: true, trigger: 'blur', message: '优惠券名称不能为空' }
        ],
        couponMoneyId: [
          { required: true, trigger: 'blur', message: '金额规则是必选项' }
        ],
        couponCategoryId: [
          { required: true, trigger: 'blur', message: '品类规则是必选项' }
        ],
        validDays: [
          { required: true, trigger: 'blur', validator: this.valiDays }
        ],
        dateRange: [
          { required: true, trigger: 'blur', message: '有效期是必选项', type: 'array' }
        ]
      }
    }
  },
  computed: {
    isModify() {
      return Object.keys(this.data).length
    },
    btnText() {
      return this.isModify ? '修改' : '新增'
    }
  },
  watch: {
    data: {
      immediate: true,
      handler(val = {}) {
        if (!Object.keys(val).length) {
          val = this.init()
        }
        // fill data
        const { couponName, couponCategoryId, couponMoneyId, validateRule, validStart, validEnd, validDays, id } = val
        const dateRange = []
        if (validStart && validEnd) {
          dateRange.push(...[dayjs(validStart).toDate(), dayjs(validEnd).toDate()])
        }
        this.formData = {
          couponName, couponCategoryId, couponMoneyId, validateRule, validStart, validEnd, validDays, dateRange, id
        }
      }
    },
    visible: {
      immediate: true,
      handler(val) {
        if (val) {
          this.getRules()
        }
      }
    }
  },
  mounted() {
    // -
  },
  methods: {
    init() {
      return {
        id: '',
        couponName: '',
        couponMoneyId: undefined,
        couponCategoryId: undefined,
        validateRule: 1,
        dateRange: [],
        validDays: undefined,
        isActive: 0
      }
    },
    valiDays(rule, value, callback) {
      const reg = /^([0-9]+)$/
      if (reg.test(value) && Number(value) > 0) {
        callback()
      } else {
        callback(new Error('有效天数是必选项, 且只能是正整数'))
      }
    },
    async getRules() {
      const { success: s1, data: d1 } = await this.$api.getMoneyRuleList({ isActive: 1 })

      if (s1) {
        this.moneyRules = d1
      }

      const { success: s2, data: d2 } = await this.$api.getCategoryRuleList({ isActive: 1, categoryIds: [] })

      if (s2) {
        this.categoryRules = d2
      }
      this.loading = false
    },
    async doSubmit() {
      this.$refs.$$form.validate(async ok => {
        const data = { ...this.formData }
        if (ok) {
          data.validDays = Number(data.validDays)

          if (data.dateRange.length) {
            const sDate = dayjs(data.dateRange[0])
            const eDate = dayjs(data.dateRange[1])
            data.validStart = sDate.isValid() ? sDate.format('YYYYMMDDHHmmss') : ''
            data.validEnd = eDate.isValid() ? eDate.format('YYYYMMDDHHmmss') : ''
          }

          delete data.dateRange

          this.loading = true

          const { success } = await this.$api[this.isModify ? 'updateCoupon' : 'addCoupon'](data)
          if (success) {
            this.$emit('close', true)
          }
          this.loading = false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.btn-area {
    text-align: right;
    padding: 0 20px 0 0;
}
</style>
